const Base = require('./base.js');
module.exports = class extends Base {

	async save(url, page = 1) {

		let goods = await think.fetch(url + page).then(res => res.json());
		console.log(goods);
		page++;
		goods.result.forEach(async(v) => {
			let data = {
				d_title: v.D_title,
				title: v.Title,
				score: v.Dsr,
				commission_queqiao: v.Commission_queqiao,
				quan_receive: v.Quan_receive,
				quan_price: v.Quan_price,
				yongjin_type: v.Yongjin_type,
				quan_time: v.Quan_time,
				jihua_link: v.Jihua_link,
				price: v.Price,
				jihua_shenhe: v.Jihua_shenhe,
				introduce: v.Introduce,
				cid: v.Cid,
				sales_num: v.Sales_num,
				quan_link: v.Quan_link,
				istmall: v.IsTmall,
				goods_id: v.GoodsID,
				commission_jihua: v.Commission_jihua,
				otth_id: v.ID,
				que_siteid: v.Que_siteid,
				commission: v.Commission,
				pic: v.Pic,
				org_price: v.Org_Price,
				quan_m_link: v.Quan_m_link,
				quan_id: v.Quan_id,
				quan_condition: v.Quan_condition,
				quan_surplus: v.Quan_surplus,
				seller_id: v.SellerID
			};
			await this.model("tbk_goods_temp").add(data);

		});

		if(goods.result.length == 50) {
			think.timeout(320).then(async() => {
				await this.save(url, page);
			});

		} else {
			await this.execute("ALTER  TABLE tbk_goods RENAME TO tbk_goods_cache");
			await this.execute("ALTER  TABLE tbk_goods_temp RENAME TO tbk_goods");
			await this.execute("ALTER  TABLE tbk_goods_cache RENAME TO tbk_goods_temp");
			await this.execute("truncate table tbk_goods_temp");
		}

	}

	async search(keyword, wxid, orginUrl) {
		let goods_num = 0;
		if(keyword.length < 10){
		goods_num = await this.where({
			'title': ['like', '%' + keyword + '%']
		}).count();
		}
		const url = think.service("url");
		let goods_list_url = '';
		if(wxid) {
			goods_list_url = `${orginUrl}/app/wxbot/goods/index?wxid=${wxid}*|*keyword=${encodeURI(keyword)}`;
		} else {
			goods_list_url = await url.create(`/app/wxmp/goods/index?keyword=` + encodeURI(keyword), orginUrl);
		}
		
		if(goods_num == 0 || keyword.length >= 10){
			const alimama = think.service("alimama");
				let res = await alimama.search(keyword);
				if(res.result_list){
					goods_num = res.total_results;
				}
		}
		

		return {
			goods_num: goods_num,
			goods_list_url: goods_list_url,
			keyword: keyword
		};
	}
	
	

};